// 是否是开发环境
const isDev = process.env.NODE_ENV === 'development'
// 要打包或者运行的内容
const target = process.env.TARGET
// 打包格式以逗号分隔
const formats = process.env.FORMATS.split(' ')
if (!target) {
  throw new Error('TARGET package must be specified via --environment flag.')
}
const commonjs = require('@rollup/plugin-commonjs')
const nodeResolve = require('@rollup/plugin-node-resolve').default
const reload = require('rollup-plugin-reload').default
const minize = require('rollup-plugin-minize').default
const worker = require('rollup-plugin-worker').default
const path = require('path')
const ts = require('rollup-plugin-typescript2')

const { packages } = require('./scripts/util')
// 要处理的内容
const packageDir = path.join(packages, target)
const resolve = p => path.resolve(packageDir, p)

const port = 8000
const pkg = require(resolve('package.json'))

function getOutputByFormat(formats, name) {
  return formats.map(format => {
    if (pkg.buildOptions) {
      if (isDev && pkg.buildOptions.format) format = pkg.buildOptions.format
    }
    return {
      file: resolve(`dist/${name}.${format}.js`),
      name,
      format,
      exports: 'default',
      sourcemap: isDev
    }
  })
}

function createConfig(output, plugins = []) {
  if (!output) {
    process.exit(1)
  }

  return {
    input: resolve('src/index.ts'),
    output,
    plugins: [
      ts({
        tsconfig: path.resolve(__dirname, 'tsconfig.json')
      }),
      nodeResolve(),
      commonjs(),
      worker({
        uglify: !isDev
      }),
      ...plugins
    ]
  }
}
function getReload() {
  if (pkg.buildOptions && pkg.buildOptions.isNotLive) return null
  return reload({
    contentBase: resolve(''),
    port
  })
}
module.exports = createConfig(getOutputByFormat(formats, target), [
  isDev ? getReload() : minize()
])
